import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Between, DeepPartial, FindOptionsWhere, Repository } from 'typeorm';
import { Timetable } from './models/timetable.entity';
import dayjs from 'dayjs';

@Injectable()
export class TimetableService {
  constructor(
    @InjectRepository(Timetable)
    private readonly TimetableRepository: Repository<Timetable>,
  ) {}

  async create(entity: DeepPartial<Timetable>): Promise<boolean> {
    const res = await this.TimetableRepository.save(
      this.TimetableRepository.create(entity),
    );
    return !!res;
  }

  async findById(id: string): Promise<Timetable> {
    return this.TimetableRepository.findOne({
      where: {
        id,
      },
    });
  }

  async updateById(
    id: string,
    entity: DeepPartial<Timetable>,
  ): Promise<boolean> {
    const existEntity = await this.findById(id);
    if (!existEntity) {
      return false;
    }
    Object.assign(existEntity, entity);
    const res = await this.TimetableRepository.save(existEntity);
    return !!res;
  }

  async findTimetables({
    where,
  }: {
    where: FindOptionsWhere<Timetable>;
  }): Promise<[Timetable[], number]> {
    return this.TimetableRepository.findAndCount({
      where,
      order: {
        createdAt: 'ASC',
      },
    });
  }

  async deleteById(id: string, userId: string): Promise<boolean> {
    const res1 = await this.TimetableRepository.update(id, {
      deletedBy: userId,
    });
    if (res1) {
      const res = await this.TimetableRepository.softDelete(id);
      if (res.affected > 0) {
        return true;
      }
    }
    return false;
  }

  // 获取七天内的课程表;
  async findTimetablesBetweenSevenDay(
    courseId: string,
  ): Promise<[Timetable[], number]> {
    const [res, total] = await this.TimetableRepository.findAndCount({
      where: {
        classDay: Between(
          dayjs().endOf('day').toDate(),
          dayjs().add(7, 'day').endOf('day').toDate(),
        ),
      },
      order: {
        classDay: 'asc',
        startTime: 'asc',
      },
    });
    const newRes = res.filter(
      (item) => JSON.parse(item.courseId).id === Number(courseId),
    );
    return [newRes, total];
  }
}
